package com.khiker.binary;

public class P67_AddBinary {
	public static String addBinary(String a, String b) {
		final char ZERO = '0', ONE = '1';
		final String x = "0";
		if (x.equals(a)) {
			return b;
		}
		if (x.equals(b)) {
			return a;
		}
		int i = a.length() - 1, j = b.length() - 1;
		int l = Math.max(a.length(), b.length());
		char[] res = new char[l + 1];
		char ia, ib, c = ZERO;
		while (i >= 0 || j >= 0) {
			ia = i < 0 ? ZERO : a.charAt(i--);
			ib = j < 0 ? ZERO : b.charAt(j--);
			if (ia == ib) {
				res[l--] = c;
				c = ia;
			} else {
				res[l--] = c == ONE ? ZERO : ONE;
			}
		}
		if (c == ONE) {
			res[0] = ONE;
			return new String(res);
		}
		return new String(res, 1, res.length - 1);
	}


	public static void main(String[] args) {
		String a = "1100";
		String b = "110";

		System.out.println(addBinary(a, b));
	}
}
